<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="btnaddBrand">添加</el-button>
        <!-- <el-button type="primary" size="mini" @click="getcloneShow">克隆管控</el-button> -->
      </div>
      <div class="table_searchs flex felx_align">
        <div class="table_search flex">
          <el-input placeholder="搜索" v-model="searchTable" class="input-with-select" size="small">
            <el-select v-model="select" slot="prepend" placeholder="请选择" class="table_select" style="width:105px">
              <el-option label="归属" value="1"></el-option>
              <el-option label="批次" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="idnameSearch"></el-button>
          </el-input>
        </div>
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- 批次管理table -->
    <el-table stripe :data="batchTable" style="width: 100%" :key="key" border fit highlight-current-row ref="tableDataRef">
      <el-table-column v-if="colData[0].istrue" prop="username" label="批次归属" min-width="150" align="center"></el-table-column>
      <el-table-column v-if="colData[1].istrue" prop="batch" label="批次名称" min-width="150" align="center" sortable></el-table-column>
      <el-table-column v-if="colData[2].istrue" prop="num" label="批次下设备数量" min-width="150" align="center" sortable></el-table-column>
      <el-table-column v-if="colData[3].istrue" prop="create_time" label="批次创立时间" min-width="150" align="center">
        <template slot-scope="scope">{{scope.row.create_time| newDate}}</template>
      </el-table-column>
      <el-table-column label="操作" min-width="150" align="center">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="geteditBatchGet(scope.row.id)">编辑</el-button>
            <el-button size="mini" @click="getdelBatch(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination background @size-change="handleSizeChange" :current-page.sync="listQuery.startSize" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]" layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 隐藏 -->
    <!-- 添加dialog表单 -->
    <div>
      <el-dialog :title="editSubjects ? '添加' : '编辑'" :visible.sync="dialogFormVisible" @close="addFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
        <el-form :model="addForm" ref="ruleForm" :rules="rules">
          <el-form-item label="批次昵称:" label-width="80px" prop="batch">
            <el-input v-model="addForm.batch" placeholder="请输入批次昵称(昵称最大不得超过60位)" :maxlength="60"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
          <el-button v-if="editSubjects" type="primary" @click="getaddBatch('ruleForm')" size="mini" round>确 定</el-button>
          <el-button v-else type="primary" @click="geteditBatch('ruleForm')" size="mini" round>编辑</el-button>
        </div>
      </el-dialog>

      <!-- 克隆批次弹窗start -->
      <el-dialog title="批次" :visible.sync="cloneShow" @close="cloneFormclose" :close-on-click-modal="false" :close-on-press-escape="false" width="30%">
        <el-form :model="cloneData" ref="cloneForm" :rules="rules">
          <el-form-item label="批次:" label-width="100px" prop="ybId">
            <el-select v-model="cloneData.ybId" placeholder="没有选中任何项" class="add_select">
              <el-option v-for="item in lotoptions" :key="item.batch" :label="item.batch" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="同步批次:" label-width="100px" prop="xbId">
            <el-select v-model="cloneData.xbId" placeholder="没有选中任何项" class="add_select">
              <el-option v-for="item in lotoptions" :key="item.batch" :label="item.batch" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cloneShow = false" size="mini" round>取 消</el-button>
          <el-button type="primary" size="mini" round @click="getbatchCloneAll('cloneForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 克隆批次弹窗end -->

      <!-- 删除弹窗start -->
      <delete-Dialog title="" :visible.sync="deleteDialogs.show" width="25%" top="40vh" @deleteEvents="deleteEvents" :deleteText="deleteDialogs.deleteText" />
      <!-- 删除弹窗end -->
    </div>
  </div>
</template>

<script>
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryBatch, addBatch, editBatchGet, editBatch, delBatch, batchCloneAll } from "@/api/equipment.js";
import deleteDialog from "@/components/deleteDialog";
import { getBatchTwo } from "@/api/equipment.js";
export default {
  components: { dynamicTable, deleteDialog },
  data() {
    var ddddd = (value) => {
      let cnReg = /([\u4e00-\u9fa5]|[\u3000-\u303F]|[\uFF00-\uFF60])/g
      let mat = value.match(cnReg)
      let length
      if (mat) {
        length = (mat.length + (value.length - mat.length) * 0.5)
        return length
      } else {
        return value.length * 0.5
      }
    }
    var validateUsername = (rule, value, callback) => {
      let leng = ddddd(value)
      if (leng > 30) {
        return callback(new Error('中文最多30位字符，英文最多60位字符'))
      } else {
        callback()
      }
    }
    // var validatorBatch = (rule, value, callback) => {
    //   var regex = new RegExp("^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9_]){1,60}$")
    //   var res = regex.test(value);
    //   if (res) {
    //     callback()
    //   } else {
    //     return callback(new Error('最大不得超过60位且只能输入英文,中文及数字,请重新输入'))
    //   }
    // }
    return {
      checkboxVal: ["批次归属", "批次名称", "批次下设备数量", "批次创立时间",],
      key: 1,
      colData: [], //动态控制table
      batchTable: [],
      total: 0, //总数量
      //添加表单
      addForm: {
        batch: "",
      },
      rules: {
        batch: [{ validator: validateUsername, trigger: "blur" }],
        ybId: [{ required: true, message: "请选择批次", trigger: "blur" }],
        xbId: [{ required: true, message: "请选择同步批次", trigger: "blur" }]
      },
      select: "", //搜索条件
      searchTable: "",
      //添加按钮控制
      dialogFormVisible: false,
      //编辑按钮控制
      editSubjects: true,
      //浏览器专题id
      subjectId: 0,
      //删除弹窗
      deleteDialogs: { show: false, deleteText: '', deleteId: 0 },
      //批次下拉选择
      lotoptions: [],
      cloneData: { ybId: '', xbId: '' },
      cloneShow: false,
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), batch: undefined, username: undefined },
    };
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal);//转为数组对象，好控制table
    this.getequipment()
    this.getBatchTwos()
  },
  methods: {
    //删除
    getdelBatch(id) {
      this.deleteDialogs.show = true
      this.deleteDialogs.deleteId = id
    },
    //删除按钮事件
    deleteEvents() {
      let params = { userId: localStorage.getItem("ID"), id: this.deleteDialogs.deleteId }
      delBatch(params).then(res => {
        this.$message.success(res.msg)
        this.getequipment()
      })
    },
    getcloneShow() {
      this.cloneShow = true
      this.getBatchTwos()
    },
    //根据ID获取批次列表
    getBatchTwos() {
      let data = { userId: localStorage.getItem("ID") }
      getBatchTwo(data).then(res => {
        this.lotoptions = res.data
      }).catch(err => {
        this.lotoptions = []
      })
    },
    //添加批次
    getaddBatch(fromName) {
      this.$refs[fromName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.userId = localStorage.getItem("ID")
          addBatch(addForm).then(res => {
            this.$message.success(res.msg)
            this.getequipment()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    getbatchCloneAll(fromName) {
      this.$refs[fromName].validate(valid => {
        if (valid) {
          let cloneData = JSON.parse(JSON.stringify(this.cloneData))
          cloneData.userId = localStorage.getItem("ID")
          batchCloneAll(cloneData).then(res => {
            this.$message.success(res.msg)
            this.getequipment()
            this.cloneShow = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //修改批次
    geteditBatch(fromName) {
      this.$refs[fromName].validate(valid => {
        if (valid) {
          let addForm = JSON.parse(JSON.stringify(this.addForm))
          addForm.userId = localStorage.getItem("ID")
          addForm.id = this.subjectId
          editBatch(addForm).then(res => {
            this.$message.success(res.msg)
            this.getequipment()
            this.dialogFormVisible = false
          }).catch(err => { })
        } else {
          return false
        }
      })
    },
    //根据ID获取信息
    geteditBatchGet(id) {
      this.editSubjects = false
      this.subjectId = id
      editBatchGet({ id: id }).then(res => {
        this.dialogFormVisible = true
        let data = res.data
        this.addForm.batch = data.batch
      }).catch(err => { })
    },
    getequipment() {
      queryBatch(this.listQuery).then(res => {
        this.batchTable = res.data
        this.total = res.total
      }).catch(err => {
        this.batchTable = []
        this.total = 0
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getequipment();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getequipment();
    },
    btnaddBrand() {
      this.editSubjects = true
      this.dialogFormVisible = true
    },
    //编辑添加表单关闭事件
    addFormclose() {
      this.$nextTick(() => {
        this.$refs.ruleForm.resetFields();
        this.addForm.batch = ''
      })
    },
    cloneFormclose() {
      this.$nextTick(() => {
        this.$refs.cloneForm.resetFields();
      })
    },
    //搜索,1:sn码,2:归属,3:批次,4:系统固件版本号,5:设备信息版本号,6:管交易版本号,7:在线
    idnameSearch() {
      if (!this.select) return this.$message.warning("请先选择查询条件");
      this.listQuery.startSize = 1
      this.listQuery.pageSize = 10
      switch (this.select) {
        case '1':
          this.listQuery.username = this.searchTable
          break;
        case '2':
          this.listQuery.batch = this.searchTable
          break;
      }
      this.getequipment();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), batch: undefined, username: undefined }
      this.getequipment()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    },
  }
};
</script>

<style lang="scss" scoped>
</style>